<!--
 * @Description: 医嘱病例
 * @Author: 梁青春
 * @Date: 2025-10-11 14:53:56
 * @LastEditTime: 2025-11-20 14:35:35
 * @LastEditors: 梁青春
-->
<template>
  <navbar>
    <template #left-pick>
      <div class="dropdown">
        <el-dropdown>
          <span class="el-dropdown-link">
            {{ selectedDept?.deptName }}
            <el-icon class="el-icon--right">
              <arrow-down />
            </el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item v-for="ward in leftDeptsList" :key="ward.id" @click="selectDept(ward)">
                {{ ward.deptName }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </template>
  </navbar>
  <Container :showLeft="true" :showRight="false" leftWidth="320px">
    <template #left>
      <div class="left-heard left-header-search">
        <el-radio-group v-model="queryParams.type" size="medium">
          <el-radio-button label="科室" value="1" />
          <el-radio-button label="我的" value="2" />
        </el-radio-group>
        <el-input
          class="search-input"
          prefix-icon="el-icon-search"
          v-model="queryParams.searchKey"
          placeholder="搜索患者/床位"
          clearable
          @change="handleSearch"
        />
      </div>
      <div class="left-body">
        <div class="todo-date">
          <div class="tabs">
            <h-tabs
              :tabs="[
                { label: '在院', value: '1', badge: 0, offset: [5, 2] },
                { label: '出院', value: '2', badge: 0, offset: [5, 2] }
              ]"
              v-model="queryParams.status"
            />
          </div>
        </div>
        <div class="patient-list">
          <div class="patient-item" v-for="item in patientList" :key="item.id" @click="handleClickPatient(item)">
            <div class="patient-icon iconfont" :class="[item.gender === '2' ? 'icon-woman' : 'icon-man']"></div>
            <div class="patient-info">
              {{ item.name }} {{ calculateAge(item.birthDate) }}
              {{ item.bedNo }}
            </div>
            <div class="patient-tags">
              <StatusTag :statusTags="item.statusTags" rootClass="orders__tags" />
            </div>
          </div>
        </div>
      </div>
    </template>
    <div class="container-body" id="containerBody">
      <div class="main-herard tabs">
        <Tabs v-model="activeTab" :tabs="tabs" @change="onTabChange" />
      </div>
      <div class="main_body" :key="activeTab" v-if="selectPatient">
        <div class="patient-title">
          <div class="title-info">
            <span>【{{ patientInfo.hospitalizationNumber }}】</span>/ <span>{{ patientInfo.name }}</span
            >/ <span>{{ patientInfo.gender === '1' ? '女' : '男' }}</span
            >/ <span>{{ calculateAge(patientInfo.birthDate) }}岁</span>/ <span>住院：{{ patientInfo.days }}天</span>/
            <span>医生：{{ patientInfo.wardName }}</span
            >/
            <span>诊断：{{ patientInfo.diagnosis }}</span>
            <StatusTag :statusTags="patientInfo.statusTags" rootClass="orders__tags" />
          </div>
          <div class="title-opt">
            <el-select class="opt-select" v-model="patientInfo.settlementType" placeholder="请选择费别">
              <el-option
                v-for="dict in sys_settlement_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
            <el-button-group>
              <el-popover placement="bottom" :width="400" trigger="click">
                <template #reference>
                  <el-button>详细资料</el-button>
                </template>
                <div class="user-order-info">
                  <div>
                    {{ patientInfo.checkInTime }}住院，在院{{ patientInfo.days }}天，入院：{{ currentYear }}年第{{
                      patientInfo.episodeNo
                    }}次/累计第{{ patientInfo.episodeNo }}次
                  </div>
                </div>
              </el-popover>
              <el-popover placement="bottom" :width="226" trigger="click">
                <template #reference>
                  <el-button>出/转/护</el-button>
                </template>
                <div class="btn-group">
                  <el-button class="btn-item" type="primary" @click="openDischargeDialog">出院</el-button>
                  <el-button class="btn-item" type="primary">转院</el-button>
                  <el-button class="btn-item" type="primary">转科</el-button>
                  <el-button class="btn-item" type="primary">护理等级</el-button>
                </div>
              </el-popover>
            </el-button-group>
          </div>
        </div>
        <component :is="activeComponent" :patient="patientInfo" />
      </div>
      <div class="main_body" v-else>
        <el-empty :image-size="120" description="暂无患者信息">
          <div class="empty-hint">请从左侧选择患者查看详细信息</div>
        </el-empty>
      </div>
    </div>
  </Container>
  <DischargeDialog v-model:visible="dischargeVisible" :patient="patientInfo" @submit="onDischargeSubmit" />
</template>

<script setup name="ClinicalRecords">
import { ref, reactive, computed, getCurrentInstance } from 'vue'
import Tabs from '@/components/Tabs/index.vue'
import DischargeDialog from './components/DischargeDialog.vue'
import useUserStore from '@/store/modules/user'
import { getPatientList } from '@/api/residentDoctor/clinicalRecords'
import Diagnosis from './Diagnosis.vue'

const { proxy } = getCurrentInstance()
const { sys_settlement_type } = proxy.useDict('sys_settlement_type')
const userStore = useUserStore()

// 左侧患者列表相关
const leftDeptsList = ref(userStore.depts)
const selectedDept = ref(leftDeptsList.value[0])
const selectPatient = ref(null)
const selectDept = dept => {
  selectedDept.value = dept
  loadPatientList()
}

// 查询参数
const queryParams = reactive({
  type: '1',
  status: '1',
  searchKey: ''
})

watch([() => queryParams.status, () => queryParams.type], () => {
  loadPatientList()
})

// 患者列表
const patientList = ref([])

// 当前患者信息
const patientInfo = computed(() => ({ ...selectPatient.value }))

const currentYear = computed(() => new Date().getFullYear())
const activeComponent = ref(Diagnosis)

// 计算年龄
const calculateAge = birthDate => {
  if (!birthDate) return ''
  const birth = new Date(birthDate)
  if (isNaN(birth)) return ''
  const today = new Date()
  let age = today.getFullYear() - birth.getFullYear()
  const month = today.getMonth() - birth.getMonth()
  const day = today.getDate() - birth.getDate()
  if (month < 0 || (month === 0 && day < 0)) {
    age--
  }
  return `${age}`
}

// 主内容区标签页
const activeTab = ref('Diagnosis')
const tabs = ref([
  { label: '医嘱', value: 'Order' },
  { label: '病历', value: 'MedicalRecord' },
  { label: '诊断', value: 'Diagnosis' },
  { label: '检查', value: 'Examination' },
  { label: '检验', value: 'Inspection' },
  { label: '体征', value: 'VitalSign' },
  { label: '费用', value: 'Fee' }
])

// 方法
const handleSearch = () => {
  // 搜索逻辑
  console.log('搜索:', queryParams.searchKey)
  loadPatientList()
}

const handleClickPatient = patient => {
  // 选择患者逻辑
  console.log('选择患者:', patient)
  selectPatient.value = patient
}

const onTabChange = tab => {
  switch (tab) {
    case 'Diagnosis':
      activeComponent.value = Diagnosis
      break
    default:
      activeComponent.value = Diagnosis
  }
}

const loadPatientList = () => {
  // 加载患者列表逻辑
  getPatientList({
    deptId: selectedDept.value.deptId,
    status: queryParams.status,
    type: queryParams.type,
    searchKey: queryParams.searchKey
  }).then(res => {
    if (res.code === 200) {
      patientList.value = res.data || []
    }
  })
}

// 出院弹窗显示状态
const dischargeVisible = ref(false)

// 打开出院弹窗
const openDischargeDialog = () => {
  dischargeVisible.value = true
}

// 出院提交处理
const onDischargeSubmit = payload => {
  // 这里可调用后端 API 完成出院流程
  console.log('出院提交数据:', payload)
}

loadPatientList()
</script>
<style scoped lang="scss">
@use '@/assets/styles/variables.module.scss' as *;
.dropdown {
  height: 100%;
  display: flex;
  align-items: center;
  cursor: pointer;
}
.left-header-search {
  display: flex;
  align-items: center;
  background: #fff;
  .search-input {
    flex: 1;
    margin-left: $padding-sm;
  }
}
.left-body {
  background: #fff;
  height: calc(100% - $sub-navbar-height);
}
.patient-list {
  padding: 0 6px;
  flex: 1;
  overflow-y: auto;
  ::-webkit-scrollbar {
    width: 8px;
    height: 8px;
  }
  ::-webkit-scrollbar-track {
    background-color: #f5f7fa;
  }
  ::-webkit-scrollbar-thumb {
    background-color: #c0c4cc;
    border-radius: 4px;
  }
  ::-webkit-scrollbar-thumb:hover {
    background-color: #909399;
  }
  .patient-item {
    display: flex;
    align-items: center;
    padding: 6px 12px;
    border-radius: 6px;
    margin-top: 6px;
    .patient-icon {
      font-size: 24px;
      margin-right: 8px;
      border-radius: 6px;
      padding: 4px 8px;
      background-color: #e4e7ed;
      color: #606266;
    }
    .patient-info {
      flex: 1;
    }
    .patient-status {
      padding: 4px 8px;
      border-radius: 4px;
      font-size: 14px;
    }
    &:last-child {
      margin-bottom: 6px;
    }
    &:hover {
      background-color: #409eff;
      color: #fff;
    }
    &.active {
      background-color: #409eff;
      color: #fff;
    }
  }
}
.tabs {
  display: flex;
  align-items: center;
}
.patient-title {
  width: 100%;
  display: flex;
  margin: 0 auto;
  height: $sub-navbar-height;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid $border-color;
  padding: 0 $padding-md;
}
.empty-hint {
  margin-top: 8px;
  font-size: 13px;
  color: var(--el-text-color-secondary);
}
.patient-info {
  font-size: $font-size;
}
.title-opt {
  flex: 1;
  display: flex;
  justify-content: flex-end;
  .opt-select {
    width: 96px;
    margin-right: $margin-sm;
  }
}
.btn-group {
  // 一行两个
  display: grid;
  grid-template-columns: repeat(2, 96px);
  grid-gap: $margin-sm;
  .btn-item {
    width: 96px;
    margin: 0;
  }
}
</style>
